package com.lujianfei.excel2json.mvp;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

public class MainModel implements MainContract.Model {

	@Override
	public String excel2json(File selectedFile) {
		List<String> keys = new LinkedList<>();
		List<List<String>> values = new LinkedList<>();

		// 1:创建workbook
		Workbook workbook = null;
		// 1:创建workbook
		try {
			workbook = Workbook.getWorkbook(selectedFile);
			// 2:获取第一个工作表sheet
			Sheet sheet = workbook.getSheet(0);
			for (int i = 0; i < sheet.getRows(); i++) {
				List<String> rowValues = new LinkedList<>();
				for (int j = 0; j < sheet.getColumns(); j++) {
					Cell cell = sheet.getCell(j, i);
					if (0 == i) {
						keys.add(cell.getContents());
					} else {
						rowValues.add(cell.getContents());
					}
				}
				if (!rowValues.isEmpty()) {
					values.add(rowValues);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != workbook) {
				// 最后一步：关闭资源
				workbook.close();
			}
		}

		JSONArray jsonArray = new JSONArray();
		for (List<String> obj : values) {
			JSONObject jsonObj = new JSONObject();
			for (int i = 0; i < keys.size(); i++) {
				jsonObj.put(keys.get(i), obj.get(i));
			}
			jsonArray.put(jsonObj);
		}

		return jsonArray.toString();
	}

}
